<?php
class APILeave extends ApiBaseClass implements RequestInterface {
    protected $employeeService;
    protected $leaveApplicationService;
    protected $leaveRequestService;

    protected $mode;
    protected $isESSMode;

    public function showAction() {

    }

    public function createAction() {
        $this -> getLeaveRequestService() -> markApprovedLeaveAsTaken();

        $leaveTypes = $this -> getElegibleLeaveTypes();

        if (count($this -> leaveTypes) <= 1) {
            $this -> _data['errors'] = 1;
            $this -> _data['message'] = 'No Leave Types with Leave Balance';
            return;
        }

        $applyLeaveForm = $this -> getApplyLeaveForm($leaveTypes);

        $overlapLeaves = 0;
        $workshiftLengthExceeded = true;

        //this section is to save leave request
        $applyLeaveForm -> bind($this -> _request -> getParameter($applyLeaveForm -> getName()));
        if ($applyLeaveForm -> isValid()) {
            try {
                $leaveParameters = $this -> getLeaveParameterObject($applyLeaveForm -> getValues());
                $success = $this -> getLeaveApplicationService() -> applyLeave($leaveParameters);

                if (!$success) {
                    $this -> _data['errors'] = 1;
                    $this -> _data['message'] = 'Failed to Submit';
                }
            } catch (LeaveAllocationServiceException $e) {
                $this -> _data['errors'] = 1;
                $this -> _data['message'] = 'Failed to Submit';
            }
        }
    }


    public function updateLeaveStatusAction() {
        if ($request -> isMethod('post')) {
            $form = new DefaultListForm( array(), array(), true);
            $form -> bind($this -> _request -> getParameter($form -> getName()));
            $changes = $this -> _request -> getParameter('leaveRequest');
            $changeType = 'change_leave_request';
            $leaveComments = $this -> _request -> getParameter('leaveComments');
            $changeComments = array();

            if (empty($changes)) {
                $changes = $request -> getParameter('leave');
                $changeType = 'change_leave';
            }

            //this is to bypass the approval/rejection comment
            foreach ($changes as $k => $v) {
                if (trim($v) != "") {
                    $changeComments[$k] = $leaveComments[$k];
                }
            }

            $changeIds = array_keys($changes);
            $empNumbers = $this -> _getLeaveChangeEmployeeNumbers($changeIds, $changeType);

            $manager = $this -> _context -> getUserRoleManager();
            $allowed = $manager -> areEntitiesAccessible('Employee', $empNumbers);

            $mode = $this->_request -> getParameter('hdnMode', null);

            if ($allowed) {
                if ($mode != LeaveListForm::MODE_MY_LEAVE_LIST && $mode != viewLeaveRequestAction::MODE_MY_LEAVE_DETAILED_LIST) {
                    $changedByUserType = SystemUser::USER_TYPE_ADMIN;
                } else {
                    $changedByUserType = SystemUser::USER_TYPE_EMPLOYEE;
                }
            } else {
                // Check if changing own leave status
                $loggedInEmpNumber = $this->_context -> getUser() -> getAttribute('auth.empNumber');

                if ((count($empNumbers) == 1) && ($empNumbers[0] == $loggedInEmpNumber)) {
                    $changedByUserType = SystemUser::USER_TYPE_EMPLOYEE;
                } else {
                    return ;
                    //$this -> forward(sfConfig::get('sf_secure_module'), sfConfig::get('sf_secure_action'));

                }
            }

            if ($form -> isValid()) {
                $this -> getLeaveRequestService() -> changeLeaveStatus($changes, $changeType, $changeComments, $changedByUserType, $this->_context->getUser()->getAttribute('auth.empNumber'));
                // $this -> getUser() -> setFlash('success', __(TopLevelMessages::UPDATE_SUCCESS));
            }
        }

    }

    /**
     *
     * @return EmployeeService
     */
    public function getEmployeeService() {
        if (!($this -> employeeService instanceof EmployeeService)) {
            $this -> employeeService = new EmployeeService();
        }
        return $this -> employeeService;
    }

    /**
     *
     * @param EmployeeService $service
     */
    public function setEmployeeService(EmployeeService $service) {
        $this -> employeeService = $service;
    }

    /**
     *
     * @return LeaveApplicationService
     */
    public function getLeaveApplicationService() {
        if (!($this -> leaveApplicationService instanceof LeaveApplicationService)) {
            $this -> leaveApplicationService = new LeaveApplicationService();
        }
        return $this -> leaveApplicationService;
    }

    /**
     *
     * @param LeaveApplicationService $service
     */
    public function setLeaveApplicationService(LeaveApplicationService $service) {
        $this -> leaveApplicationService = $service;
    }

    /**
     *
     * @return LeaveRequestService
     */
    public function getLeaveRequestService() {
        if (!($this -> leaveRequestService instanceof LeaveRequestService)) {
            $this -> leaveRequestService = new LeaveRequestService();
        }
        return $this -> leaveRequestService;
    }

    /**
     *
     * @param LeaveRequestService $service
     */
    public function setLeaveRequestService(LeaveRequestService $service) {
        $this -> leaveRequestService = $service;
    }

    protected function getLeaveParameterObject(array $formValues) {

        $time = $formValues['time'];
        $formValues['txtFromTime'] = $time['from'];
        $formValues['txtToTime'] = $time['to'];

        return new LeaveParameterObject($formValues);
    }

    /**
     * Retrieve Eligible Leave Type
     */
    protected function getElegibleLeaveTypes() {
        $leaveTypeChoices = array();
        $empId = $_SESSION['empNumber'];
        // TODO: Use a session manager
        $employeeService = $this -> getEmployeeService();
        $employee = $employeeService -> getEmployee($empId);

        $leaveRequestService = $this -> getLeaveRequestService();
        $leaveTypeList = $leaveRequestService -> getEmployeeAllowedToApplyLeaveTypes($employee);

        $leaveTypeChoices[''] = '--' . __('Select') . '--';
        foreach ($leaveTypeList as $leaveType) {
            $leaveTypeChoices[$leaveType -> getId()] = $leaveType -> getName();
        }

        return $leaveTypeChoices;
    }

    /**
     * Creating user forms
     */
    protected function getApplyLeaveForm($leaveTypes) {
        $form = new ApplyLeaveForm( array(), array('leaveTypes' => $leaveTypes), true);
        return $form;
    }

    protected function _getLeaveChangeEmployeeNumbers($changes, $changeType) {

        $empNumbers = array();
        $leaveRequestService = $this -> getLeaveRequestService();

        if ($changeType == 'change_leave_request') {
            $leaveRequestService = $this -> getLeaveRequestService();
            foreach ($changes as $id) {
                $leaveRequest = $leaveRequestService -> fetchLeaveRequest($id);
                $empNumbers[] = $leaveRequest -> getEmpNumber();
            }
        } else {

            foreach ($changes as $id) {
                $leave = $leaveRequestService -> getLeaveById($id);
                $empNumbers[] = $leave -> getEmpNumber();
            }
        }

        return array_unique($empNumbers);
    }

}
?>